﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using nanoCMS.Core;
using nanoCMS.Forum.Concrete;

namespace nanoCMS.Forum.Providers
{
    public class PostProvider
    {
        private readonly WorldContext worldContext;
        private ForumEntities _entities; //DO NOT ACCESS DIRECTLY
        private ForumEntities Entities
        {
            get { return _entities ?? (_entities = new ForumEntities(worldContext.EntityConnectionString)); }
        }

        public PostProvider(WorldContext worldContext)
        {
            this.worldContext = worldContext;
        }

        public Post CreatePost(int userId, int threadID, string title, string content, DateTime postTime)
        {
            // create new post
            Post newPost = new Post()
            {
                UserID = userId,
                Content = content,
                PostTime = postTime,
                ThreadID = threadID, 
                Title = title
            };
            Entities.Posts.AddObject(newPost);
            // update forums posts
            Entities.SaveChanges();
            return newPost; 
        }

        public Post GetPost(int postID)
        {
            return Entities.Posts.Where(p => p.PostID == postID).SingleOrDefault(); 
        }

        public List<Post> GetThreadPosts(int threadID, int page, int postsPerPage)
        {
            return  Entities.Posts.Where(p => p.ThreadID == threadID).OrderBy(t => t.PostTime).Skip(
                page*postsPerPage).Take(postsPerPage).ToList(); 
        }

        public List<Post> GetThreadPosts(int threadID)
        {
            return Entities.Posts.Where(p => p.ThreadID == threadID).ToList();
        }

        public Post GetLastPost(int threadId)
        {
            return Entities.Posts.Where(p => p.ThreadID == threadId).OrderByDescending(
                t => t.PostTime).SingleOrDefault(); 
        }

        public Post EditPost(int postID, string title, string content)
        {
            Post post = Entities.Posts.Where(p => p.PostID == postID).SingleOrDefault(); 
            if(post != null)
            {
                post.Title = title;
                post.Content = content; 
            }
            Entities.ObjectStateManager.ChangeObjectState(post, EntityState.Modified);
            Entities.SaveChanges();
            return post; 
        }

        public void DeletePost(int postID)
        {
            Post post = GetPost(postID);
            // ThreadID = 0 ==> post is post thread, so - no delete
            if(post != null && post.ThreadID != 0)
            {
                Entities.DeleteObject(post);
                // update thread posts
                Entities.SaveChanges(); 
            }
        }
    }
}
